package dyyx;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;


@Activate(group = {Constants.PROVIDER, Constants.CONSUMER},order=-100000)
public class TraceIdFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String traceId = RpcContext.getContext().getAttachment("traceId");
        
    
        if ( !StringUtils.isEmpty(traceId) ) {
            // 从RpcContext里获取traceId并保存
            TraceIdUtils.setTraceId(traceId);
        } else {
        	// 没有设置或被清空了
        	String traceId2 = TraceIdUtils.getTraceId();
        	
            // 发起 rpc调用 重新设置traceId 
        	if ( !StringUtils.isEmpty(traceId2) ) {
                RpcContext.getContext().setAttachment("traceId", traceId2);
        	}
        }
        // 实际的rpc调用
        try {
            return invoker.invoke(invocation);
        }finally{
        	// 清理
        	TraceIdUtils.clear();
        }
    }

}


